package org.mspring.platform.utils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 驼峰命名法
 *
 * @since 2014-03-27 09:58:46
 * @author Gao Youbo
 */
public class CamelCaseUtils {

    private static final char SEPARATOR = '_';

    /**
     * HelloWorld => helloWorld, hello_world => helloWorld
     *
     * @param s
     * @return
     */
    public static String toCamelCase(String s) {
        Matcher matcher = Pattern.compile("_[a-z]").matcher(s);
        StringBuilder builder = new StringBuilder(s);
        for (int i = 0; matcher.find(); i++) {
            builder.replace(matcher.start() - i, matcher.end() - i, matcher.group().substring(1).toUpperCase());
        }
        if (Character.isUpperCase(builder.charAt(0))) {
            builder.replace(0, 1, String.valueOf(Character.toLowerCase(builder.charAt(0))));
        }
        return builder.toString();
    }

    /**
     * helloWorld => hello_world
     *
     * @param s
     * @return
     */
    public static String toUnderScoreCase(String s) {
        if (s == null) {
            return null;
        }
        StringBuilder sb = new StringBuilder();
        boolean upperCase = false;
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            boolean nextUpperCase = true;
            if (i < (s.length() - 1)) {
                nextUpperCase = Character.isUpperCase(s.charAt(i + 1));
            }
            if ((i > 0) && Character.isUpperCase(c)) {
                if (!upperCase || !nextUpperCase) {
                    sb.append(SEPARATOR);
                }
                upperCase = true;
            } else {
                upperCase = false;
            }
            sb.append(Character.toLowerCase(c));
        }
        return sb.toString();
    }

    /**
     * hello_world => HelloWorld
     *
     * @param s
     * @return
     */
    public static String toCapitalizeCamelCase(String s) {
        if (s == null) {
            return null;
        }
        s = toCamelCase(s);
        return s.substring(0, 1).toUpperCase() + s.substring(1);
    }
}
